package com.pengshun.modules.security;

import com.pengshun.modules.api.mapper.PsUserInfoMapper;
import com.pengshun.modules.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @author
 */
@Component
public class CurrUserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private PsUserInfoMapper psUserInfoMapper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (methodParameter.getParameterType().isAssignableFrom(CurrUser.class) &&
                methodParameter.hasParameterAnnotation(CurrUserInfo.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String token = request.getParameter("jwtToken");
        SelfUserDetails details = (SelfUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        User info = psUserInfoMapper.findUserByPhone(details.getUsername());
        Long uiId = info.getId();
        String name = info.getName();
        String phone = info.getPhone();
        return new CurrUser(uiId,name,phone);
    }

}
